package com.bringspring.visualdev.onlinedev.util.onlineDevUtil;

import com.bringspring.common.model.FormEnum;
import com.bringspring.common.model.FormModel;
import com.bringspring.common.model.visiual.ComponentKeyConsts;
import com.bringspring.common.model.visiual.OnlineDevData;
import com.bringspring.common.model.visiual.fields.FieLdsModel;
import com.bringspring.common.model.visiual.fields.config.ConfigModel;
import com.bringspring.common.util.JsonUtil;
import com.bringspring.common.util.StringUtils;
import com.bringspring.visualdev.onlinedev.model.OnlineDevEnum.MultipleControlEnum;
import com.bringspring.visualdev.onlinedev.model.OnlineDevListModel.OnlineConfigModel;
import com.bringspring.visualdev.onlinedev.model.OnlineDevListModel.OnlineFieldsModel;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 在线开发公用
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date  2021/7/28
 */
public class OnlinePublicUtils {
	/**
	 * 判断有表无表
	 * @return
	 */
	public static Boolean isUseTables(String tableJson){
			if (!StringUtils.isEmpty(tableJson) && !OnlineDevData.TABLE_CONST.equals(tableJson)) {
				return true;
			}
				return false;
		}

	/**
	 * map key转小写
	 * @param requestMap
	 * @return
	 */
	public static Map<String, Object> mapKeyToLower(Map<String, ?> requestMap) {
		// 非空校验
		if (requestMap.isEmpty()) {
			return null;
		}
		// 初始化放转换后数据的Map
		Map<String, Object> responseMap = new HashMap<>(16);
		// 使用迭代器进行循环遍历
		Set<String> requestSet = requestMap.keySet();
		Iterator<String> iterator = requestSet.iterator();
		iterator.forEachRemaining(obj -> {
			// 判断Key对应的Value是否为Map
			if ((requestMap.get(obj) instanceof Map)) {
				// 递归调用，将value中的Map的key转小写
				responseMap.put(obj.toLowerCase(), mapKeyToLower((Map) requestMap.get(obj)));
			} else {
				// 直接将key小写放入responseMap
				responseMap.put(obj.toLowerCase(), requestMap.get(obj));
			}
		});

		return responseMap;
	}


	/**
	 * 获取map中第一个数据值
	 *
	 * @param map 数据源
	 * @return
	 */
	public static Object getFirstOrNull(Map<String, Object> map) {
		Object obj = null;
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			obj = entry.getValue();
			if (obj != null) {
				break;
			}
		}
		return  obj;
	}

	/**
	 * 去除列表里无用的控件
	 * @param fieldsModelList
	 * @return
	 */
	public static void removeUseless(List<OnlineFieldsModel> fieldsModelList) {
		for (int i = 0 ; i<fieldsModelList.size();i++){
			if (fieldsModelList.get(i).getConfig().getKeyName()==null){
				continue;
			}
			if (fieldsModelList.get(i).getConfig().getKeyName().equals(ComponentKeyConsts.CHILD_TABLE)){
				fieldsModelList.remove(i);
			}
		}
	}


	/**
	 * 递归控件
	 * @param fieldsModelList
	 * @return
	 */
	public static void recursionFields(List<OnlineFieldsModel> fieldsModelList,List<OnlineFieldsModel> allFieldsModelList){
		//去除子表控件
		removeUseless(fieldsModelList);
		for (OnlineFieldsModel model:fieldsModelList){
			if (model.getConfig().getChildren()!=null){
				recursionFields(model.getConfig().getChildren(),allFieldsModelList);
			}
			allFieldsModelList.add(model);
		}
	}

	/**
	 * 判断字符串是否以某个字符开头
	 * @param var1 完整字符串
	 * @param var2 统计字符
	 * @return
	 */
	public static Boolean getMultiple(String var1,String var2){
		if (var1.startsWith(var2)){
			return true;
		}
			return false;
	}

	/**
	 *  数据字典处理（从缓存中取出）
	 * @param dataList
	 * @param swapModel
	 * @return
	 */
	public static Map<String,Object> getDataMap(List<Map<String,Object>> dataList, FieLdsModel swapModel) {
		String label;
		String value;
		if (swapModel.getConfig().getKeyName().equals(ComponentKeyConsts.CASCADER) || swapModel.getConfig().getKeyName().equals(ComponentKeyConsts.TREESELECT)) {
			label = swapModel.getProps().getPropsModel().getLabel();
			value = swapModel.getProps().getPropsModel().getValue();
		} else {
			label = swapModel.getConfig().getProps().getLabel();
			value = swapModel.getConfig().getProps().getValue();
		}
		Map<String,Object> dataInterfaceMap = new HashMap<>();
		dataList.stream().forEach(data->{
			dataInterfaceMap.put(String.valueOf(data.get(value)),String.valueOf(data.get(label)));
		});
		return dataInterfaceMap;
	}

	public static Map<String,Object> getDataMap(List<Map<String,Object>> dataList, OnlineFieldsModel swapModel) {
		String label;
		String value;
		if (swapModel.getConfig().getKeyName().equals(ComponentKeyConsts.CASCADER) || swapModel.getConfig().getKeyName().equals(ComponentKeyConsts.TREESELECT)) {
			label = swapModel.getProps().getProps().getLabel();
			value = swapModel.getProps().getProps().getValue();
		} else {
			label = swapModel.getConfig().getProps().getLabel();
			value = swapModel.getConfig().getProps().getValue();
		}
		Map<String,Object> dataInterfaceMap = new HashMap<>();
		dataList.stream().forEach(data->{
			dataInterfaceMap.put(String.valueOf(data.get(value)),String.valueOf(data.get(label)));
		});
		return dataInterfaceMap;
	}
	/**
	 * 获取时间(+8)
	 * @param date
	 * @param format
	 * @return
	 */
	public static String getDateByFormat(Long date,String format){
		DateTimeFormatter ftf = DateTimeFormatter.ofPattern(format);
		String dateString = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneId.of("+8")));
		return dateString;
	}

	/**
	 * 递归表单控件
	 * @param modelList 所有控件
	 * @param mainFields 主表
	 * @param childFields 子表
	 * @param models 二维码 条形码
	 */
	public static void recurseFiled(List<FieLdsModel> modelList, List<FieLdsModel> mainFields, List<FieLdsModel> childFields, List<FormModel> models){
		for (FieLdsModel fieLdsModel : modelList){
			ConfigModel config = fieLdsModel.getConfig();
			String keyName = config.getKeyName();
			List<FieLdsModel> childrenList = config.getChildren();
			boolean isKeyName = StringUtils.isEmpty(keyName);
			if (FormEnum.row.getMessage().equals(keyName) || FormEnum.card.getMessage().equals(keyName)
					|| FormEnum.tab.getMessage().equals(keyName) || FormEnum.collapse.getMessage().equals(keyName)
					|| isKeyName){
				if (childrenList.size()>0){
					recurseFiled(childrenList,mainFields,childFields,models);
				}else {
					mainFields.add(fieLdsModel);
				}
			}else if (FormEnum.table.getMessage().equals(keyName)) {
					childFields.add(fieLdsModel);
			} else if (FormEnum.groupTitle.getMessage().equals(keyName) || FormEnum.divider.getMessage().equals(keyName) || FormEnum.ComText.getMessage().equals(keyName)) {

			}else if (FormEnum.QR_CODE.getMessage().equals(keyName) || FormEnum.BARCODE.getMessage().equals(keyName)){
				FormModel formModel = JsonUtil.getJsonToBean(fieLdsModel, FormModel.class);
				models.add(formModel);
			}else {
				mainFields.add(fieLdsModel);
			}
		}
	}

	public static void recurseOnlineFiled(List<OnlineFieldsModel> modelList,List<OnlineFieldsModel> mainFields,List<OnlineFieldsModel> childFields){
		for (OnlineFieldsModel fieLdsModel : modelList){
			OnlineConfigModel config = fieLdsModel.getConfig();
			String keyName = config.getKeyName();
			List<OnlineFieldsModel> childrenList = config.getChildren();
			boolean isKeyName = StringUtils.isEmpty(keyName);
			if (FormEnum.row.getMessage().equals(keyName) || FormEnum.card.getMessage().equals(keyName)
					|| FormEnum.tab.getMessage().equals(keyName) || FormEnum.collapse.getMessage().equals(keyName)
					|| isKeyName){
				if (childrenList.size()>0){
					recurseOnlineFiled(childrenList,mainFields,childFields);
				}else {
					mainFields.add(fieLdsModel);
				}
			}else if (FormEnum.table.getMessage().equals(keyName)) {
				childFields.add(fieLdsModel);
			} else if (FormEnum.groupTitle.getMessage().equals(keyName) || FormEnum.divider.getMessage().equals(keyName) || FormEnum.ComText.getMessage().equals(keyName)) {

			} else {
				mainFields.add(fieLdsModel);
			}
		}
	}

	/**
	 *
	 * @param redisMap 缓存集合
	 * @param modelData  数据
	 * @param isMultiple 是否多选
	 * @return
	 */
	public static String getDataInMethod(Map<String, Object> redisMap, Object modelData,Boolean isMultiple) {
		if (redisMap == null || redisMap.isEmpty()) {
			return modelData.toString();
		}
		String Separator = isMultiple ? ";" : "/";
		String s2;
		if (OnlinePublicUtils.getMultiple(String.valueOf(modelData), MultipleControlEnum.MULTIPLE_JSON_TWO.getMultipleChar())) {
			String[][] data = JsonUtil.getJsonToBean(String.valueOf(modelData), String[][].class);
			List<String> addList = new ArrayList<>();
			for (String[] AddressData : data) {
				List<String> adList = new ArrayList<>();
				for (String s : AddressData) {
					adList.add(String.valueOf(redisMap.get(s)));
				}
				addList.add(String.join("/", adList));
			}
			s2 = String.join(";", addList);
		} else if (OnlinePublicUtils.getMultiple(String.valueOf(modelData), MultipleControlEnum.MULTIPLE_JSON_ONE.getMultipleChar())) {
			List<String> modelDataList = JsonUtil.getJsonToList(String.valueOf(modelData), String.class);
			modelDataList = modelDataList.stream().map(s -> String.valueOf(redisMap.get(s))).collect(Collectors.toList());
			s2 = String.join(Separator, modelDataList);
		} else {
			String[] modelDatas = String.valueOf(modelData).split(",");
			StringBuilder dynamicData = new StringBuilder();
			for (int i = 0; i < modelDatas.length; i++) {
				modelDatas[i] = String.valueOf(redisMap.get(modelDatas[i]));
				dynamicData.append(modelDatas[i] + Separator);
			}
			s2 = dynamicData.deleteCharAt(dynamicData.length() - 1).toString();
		}
		return StringUtils.isEmpty(s2) ? modelData.toString() : s2;
	}

}

